package org.example.mock;

import com.github.javafaker.Faker;
import org.example.bean.Inventory;

import java.sql.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class InventoryDataGenerator {
 private static final String DB_URL = "jdbc:mysql://hadoop102/bookstore?useSSL=false&requireSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "000000";
    private static final int BATCH_SIZE = 100;
    private static final Faker faker = new Faker(Locale.CHINA);

    public static void main(String[] args) {
        int count = 1000; // 默认生成500条数据
        if (args.length >= 1) count = Integer.parseInt(args[0]);
        generateData(count);
    }

    public static void generateData(int count) {
        // 获取已有的店铺ID和图书ID
        List<String> storeIds = fetchStoreIds();
        List<String> bookIds = fetchBookIds();

        if (storeIds.isEmpty() || bookIds.isEmpty()) {
            System.err.println("错误：请先生成店铺和图书数据");
            return;
        }

        List<Inventory> inventories = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();

        for (int i = 0; i < count; i++) {
            Inventory inventory = Inventory.builder()
                    .storeId(storeIds.get(faker.random().nextInt(storeIds.size())))
                    .bookId(bookIds.get(faker.random().nextInt(bookIds.size())))
                    .currentStock(faker.number().numberBetween(5, 100))
                    .safetyStock(faker.number().numberBetween(10, 30))
                    .lastCheckDate(LocalDate.now().minusDays(faker.number().numberBetween(1, 30)))
                    .lastDeliveryDate(LocalDate.now().minusDays(faker.number().numberBetween(1, 60)))
                    .createTime(now)
                    .updateTime(now)
                    .build();
            inventories.add(inventory);
        }

        insertData(inventories);
    }

    private static List<String> fetchStoreIds() {
        List<String> ids = new ArrayList<>();
        String sql = "SELECT store_id FROM store_info";
        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            while (rs.next()) {
                ids.add(rs.getString("store_id"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return ids;
    }

    private static List<String> fetchBookIds() {
        List<String> ids = new ArrayList<>();
        String sql = "SELECT book_id FROM book_info";
        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            while (rs.next()) {
                ids.add(rs.getString("book_id"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return ids;
    }

    private static void insertData(List<Inventory> inventories) {
        String sql = "INSERT INTO inventory (store_id, book_id, current_stock, safety_stock, " +
                "last_check_date, last_delivery_date, create_time, update_time) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?, ?)";

        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD)) {
            conn.setAutoCommit(false);
            try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
                for (int i = 0; i < inventories.size(); i++) {
                    Inventory inventory = inventories.get(i);
                    pstmt.setString(1, inventory.getStoreId());
                    pstmt.setString(2, inventory.getBookId());
                    pstmt.setInt(3, inventory.getCurrentStock());
                    pstmt.setInt(4, inventory.getSafetyStock());
                    pstmt.setDate(5, Date.valueOf(inventory.getLastCheckDate()));
                    pstmt.setDate(6, Date.valueOf(inventory.getLastDeliveryDate()));
                    pstmt.setTimestamp(7, Timestamp.valueOf(inventory.getCreateTime()));
                    pstmt.setTimestamp(8, Timestamp.valueOf(inventory.getUpdateTime()));
                    pstmt.addBatch();

                    if ((i + 1) % BATCH_SIZE == 0) pstmt.executeBatch();
                }
                pstmt.executeBatch();
                conn.commit();
                System.out.println("成功插入" + inventories.size() + "条库存数据");
            } catch (SQLException e) {
                conn.rollback();
                e.printStackTrace();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}